package com.edu.whty.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.*;
import com.edu.whty.dao.AttachFileDao;
import com.edu.whty.dao.TbCourseResMapper;
import com.edu.whty.dao.TbCourseUserMapper;
import com.edu.whty.entity.base.AttachFile;
import com.edu.whty.entity.base.CloudPage;
import com.edu.whty.entity.base.PageInfo;
import com.edu.whty.entity.cloud.*;
import com.edu.whty.service.CourseService;
import com.edu.whty.service.base.impl.CommonServiceImpl;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("courseService")
public class CourseServiceImpl extends CommonServiceImpl implements CourseService {

    private Logger logger = LoggerFactory.getLogger(CourseServiceImpl.class);

    @Autowired
    private TbCourseUserMapper tbCourseUserMapper;

    @Autowired
    TbCourseResMapper tbCourseResMapper;

    @Autowired
    AttachFileDao attachFileDao;

    @Value("${rrtbk.isCloud}")
    private boolean isCloud;

    @Value("${rrtbk.uploadUrl}")
    private String uploadUrl;

    @Value("${rrtbk.url}")
    private String rrtbkUrl;

    @Value("${rrtbk.api.updateStat}")
    private String updateStat;


    @Override
    public void moveCloud(MoveCloudReq moveCloud) {
        List<String> ids = new ArrayList<String>();
        for (CloudId id : moveCloud.getList()) {
            ids.add(id.getCourseId());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ids", ids);
        param.put("courseUserid", moveCloud.getUserId());
        param.put("courseChapterid", moveCloud.getChapterId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		param.put("modifyTime", sdf.format(new Date()));
        tbCourseUserMapper.moveCloud(param);
    //修改时间涉及分表暂时移除

    }

    public void fillPara(UserResRequest2 userRes,AttachFile attachFile){
        if("null".equals(userRes.getFileLength())){
            userRes.setFileLength(null);
        }
        attachFile.setFileLength(StringUtils.isBlank(userRes.getFileLength())?0L:Long.parseLong(userRes.getFileLength()));
        attachFile.setFileNameLocal(userRes.getTitle());
        attachFile.setFileNameRemote(UUID.randomUUID().toString().replaceAll("-", "") + "." + userRes.getFileExt());
        String filePath = FileUtil.getCosKey(attachFile.getFileNameRemote(), userRes.getUserId(), userRes.getLoginPlatformCode());
        attachFile.setFilePathLocal(filePath);
        attachFile.setFilePathRemote(filePath);
        attachFile.setFilePos(Long.parseLong(userRes.getFileLength()));
        attachFile.setFileSize(userRes.getFileSize());
        attachFile.setFileExt(userRes.getFileExt());
        attachFile.setIsDeleted("false");
        attachFile.setPostComplete("true");
        attachFile.setPostedLength(Long.parseLong(userRes.getFileLength()));
        attachFile.setPostedPercent("100%");
        attachFile.setPostedTime(new Date());
        attachFile.setUserId(userRes.getUserId());
        attachFile.setIsFileCenter(StringUtils.isNotBlank(userRes.getIsFileCenter()) ? Integer.parseInt(userRes.getIsFileCenter()) : 0);
        attachFile.setPlatformCode(userRes.getLoginPlatformCode());
        attachFile.setOrgId(userRes.getOrgId());
        if(StringUtils.isNotBlank(userRes.getDownloadUrl())) {
            attachFile.setIsLocal("0");
            attachFile.setIsCloud("1");
        }else{
            attachFile.setIsLocal("1");
            attachFile.setIsCloud("0");
        }
        attachFile.setIsPlatform("1");
        attachFile.setAttachFrom("1");
        attachFile.setDownloadUrl(userRes.getDownloadUrl());
    }

    @Override
    public Map<String, Object> saveCloudRes(List<UserResRequest2> userReslist,String isPackage,String flag) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List array = new ArrayList();
        StringBuilder classfiitonIds = new StringBuilder();
        List<String> fidList = new ArrayList<String>();
        String packageId = UUIDUtils.getRandomUUID();
        List<String> returnCourseIdList = new ArrayList<String>();
        List<String> returnRseIdList = new ArrayList<String>();
        for(int i=0;i<userReslist.size();i++) {
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
            String courseId = UUIDUtils.getRandomUUID();
            returnCourseIdList.add(courseId);
            UserResRequest2 userRes = userReslist.get(i);
            AttachFile attachFile = new AttachFile();
            if("cloud".equals(flag)) {
                if(StringUtils.isNotBlank(userRes.getFId())){
                    //attachFile.setFid(Long.parseLong(userRes.getFId()));
                    AttachFile old = attachFileDao.selectOne(Long.parseLong(userRes.getFId()));
                    if(old!=null) {
                        BeanUtils.copyProperties(old, attachFile);
                        if(StringUtils.isNotBlank(userRes.getDownloadUrl())) {
                            attachFile.setIsLocal("0");
                            attachFile.setIsCloud("1");
                        }else{
                            attachFile.setIsLocal("1");
                            attachFile.setIsCloud("0");
                        }
                    }else{
                        attachFile.setFid(Long.parseLong(userRes.getFId()));
                        fillPara(userRes,attachFile);
                        attachFileDao.insertOne(attachFile);
                    }
                }else{
                    attachFile.setFid(SnowflakeUtils.getNextId());
                    fillPara(userRes,attachFile);
                    attachFileDao.insertOne(attachFile);
                }
                logger.info("fid:" + attachFile.getFid());

            }else{
                attachFile.setFid(Long.parseLong(userRes.getFId()));
            }
            TbCourseRes tbCourseRes = new TbCourseRes();
            String uid = UUIDUtils.getRandomUUID();
            userRes.setResId(uid);
            returnRseIdList.add(uid);
            tbCourseRes.setClassfiitonId(userRes.getClassfiitonTypeId());
            if(i == 0){
                classfiitonIds.append(userRes.getClassfiitonTypeId());
            }else {
                classfiitonIds.append(",").append(userRes.getClassfiitonTypeId());
            }
            tbCourseRes.setCollectedCount(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tbCourseRes.setCreateTime(sdf.format(new Date()));
            //资源有下载地址，有fid。备课才关联附件
            if(StringUtils.isNotBlank(userRes.getFId())){
                tbCourseRes.setFid(userRes.getFId());
            }
            fidList.add(String.valueOf(attachFile.getFid()));


            tbCourseRes.setSrcFid(userRes.getFId());
            tbCourseRes.setFileExt(userRes.getFileExt());
            tbCourseRes.setFileSize(userRes.getFileSize());
            tbCourseRes.setIntro(userRes.getIntro());
            tbCourseRes.setTitle(userRes.getTitle());
            tbCourseRes.setThumbnailUrl(userRes.getThumbnailUrl());
            tbCourseRes.setCreatorId(userRes.getUserId());
            tbCourseRes.setCreatorName(userRes.getUserName());
            tbCourseRes.setModifyTime(sdf.format(new Date()));
            tbCourseRes.setResId(uid);
            tbCourseRes.setMd5(userRes.getMd5());
            tbCourseRes.setCourseId(courseId);
            tbCourseRes.setUserLocalPath(userRes.getUserLocalPath());
            tbCourseRes.setOrgId(userRes.getOrgId());
            tbCourseRes.setOrgName(userRes.getOrgName());
            tbCourseRes.setResDownloadUrl(userRes.getResDownloadUrl());
            tbCourseRes.setResViewUrl(userRes.getResViewUrl());
            tbCourseRes.setH5Data("1");
            tbCourseRes.setCoursewareId(userRes.getCoursewareId());
            tbCourseRes.setSubFileExt(userRes.getSubFileExt());
            tbCourseRes.setJxzsResType(userRes.getJxzsResType());
            if(StringUtils.isNotEmpty(userRes.getPlatformProductCode())) {
                tbCourseRes.setPlatformProductCode(userRes.getPlatformProductCode());
            }
            if(StringUtils.isNotEmpty(userRes.getPlatformResId())) {
                tbCourseRes.setPlatformResId(userRes.getPlatformResId());
            }
            if (StringUtils.isEmpty(userRes.getSourceFrom())) {
                tbCourseRes.setResSource("0");
            } else if ("1".equals(userRes.getSourceFrom())) {
                tbCourseRes.setResSource("1");    //3腾讯云，0非慧教云（默认0）;1CMS存储
            } else if ("2".equals(userRes.getSourceFrom())) {
                tbCourseRes.setResSource("3"); //3腾讯云，0非慧教云（默认0）;1CMS存储
            } else if ("5".equals(userRes.getSourceFrom())) { //5阿里云存储
                tbCourseRes.setResSource("5");
            }else if ("4".equals(userRes.getSourceFrom())) { //教学助手导入
                tbCourseRes.setResSource("4");
            }

            String previewUrl = userRes.getPreviewUrl();
            String downloadUrl = userRes.getDownloadUrl();

            if (StringUtils.isEmpty(previewUrl)) {
               if ("2".equals(userRes.getSourceFrom())) {
                    //从properties 文件获取配置
                    previewUrl = SysConfig.getStrValue("cosPreviewUrl")+attachFile.getFid();
                } /*else {//没有预览地址直接不显示
                    if(Constant.picList.contains(tbCourseRes.getFileExt().toLowerCase())||Constant.videoList.contains(tbCourseRes.getFileExt().toLowerCase())){
                        previewUrl = userRes.getDownloadUrl();
                    }
                }*/
            }

            tbCourseRes.setPreviewUrl(previewUrl);

            /**
             * 上传腾讯云的互动资源tir包，使用云函数解压，拼接预览地址
             */
            if ("tir".equals(userRes.getFileExt())
                    && "2".equals(userRes.getSourceFrom())
                    && StringUtils.isNotEmpty(userRes.getResViewUrl())) {
                String cos_jxzs_url = SysConfig.getStrValue("cos_jxzs_url");
                String baseUrl = cos_jxzs_url + userRes.getResViewUrl().substring(0, userRes.getResViewUrl().lastIndexOf("."));
                previewUrl = baseUrl + "/index.html";

                tbCourseRes.setPreviewUrl(previewUrl);
                tbCourseRes.setResViewUrl(previewUrl);
            }


            if (StringUtils.isEmpty(downloadUrl)) {
                // sourceForm=1 表示资源来自网盘  ;sourceForm=2腾讯云资源上传
                if ("1".equals(userRes.getSourceFrom())) {
                    String localCmsFt = SysConfig.getStrValue("localCmsFt");
                    downloadUrl = localCmsFt + "/cms-ft/download?fid=";
                } else if ("2".equals(userRes.getSourceFrom())) {
                    downloadUrl = SysConfig.getStrValue("cosDownloadUrl");
                } else {
                    downloadUrl = SysConfig.getStrValue("downloadUrl");
                    if (StringUtils.isEmpty(downloadUrl)) {
                        downloadUrl = SysConfig.getStrValue("downloadUrl", Constant.PLATFORM_CODE_DEFAULT);
                    }
                }
                downloadUrl = downloadUrl + userRes.getFId();
            }
            tbCourseRes.setDownUrl(downloadUrl);


            if (StringUtils.isEmpty(userRes.getFileLength())) {
                tbCourseRes.setFileLength(String.valueOf(CovertUtil.covertFile(userRes.getFileSize())));
            } else {
                tbCourseRes.setFileLength(userRes.getFileLength());
            }
            tbCourseRes.setPlatformCode(userRes.getPlatformCode());
            tbCourseRes.setLoginPlatformCode(userRes.getLoginPlatformCode());

            if (StringUtils.isNotEmpty(userRes.getSelLabelId())) {
                tbCourseRes.setSelLabelId(userRes.getSelLabelId());
            }
            if (StringUtils.isNotEmpty(userRes.getSelLabelName())) {
                tbCourseRes.setSelLabelName(userRes.getSelLabelName());
            }
            if (null == tbCourseRes.getResSource() || StringUtil.isEmpty(tbCourseRes.getResSource())) {
                if (StringUtils.isNotEmpty(tbCourseRes.getDownUrl()) && tbCourseRes.getDownUrl().contains("filecenter.huijiaoyun.com")) {
                    tbCourseRes.setResSource("3");
                } else {
                    tbCourseRes.setResSource("0");
                }
            }
            if(Constant.IS_PACKAGE.equals(isPackage)){
                tbCourseRes.setIsPackage(packageId);
            }

            tbCourseRes.setInteractNameCh(userRes.getInteractNameCh());
            tbCourseRes.setInteractNameEn(userRes.getInteractNameEn());
            tbCourseResMapper.save(tbCourseRes);
            if(!(Constant.IS_PACKAGE.equals(isPackage)&&i != userReslist.size()-1)){
                TbCourseUser courseUser = new TbCourseUser();
                courseUser.setCourseId(courseId);
                courseUser.setJoinBk(userRes.getJoinBk());
                courseUser.setCourseUserid(userRes.getUserId());
                courseUser.setCourseUsername(userRes.getUserName());
                courseUser.setCourseCreateTime(sdf.format(new Date()));
                courseUser.setCourseModifyTime(sdf.format(new Date()));
                courseUser.setCourseResid(uid);
                courseUser.setCourseStatus(Constant.COURSE_STATUS);
                if (null == userRes.getResType() || StringUtil.isEmpty(userRes.getResType())) {
                    courseUser.setCourseType(Constant.COURSE_TYPE_CREATE_BY_MY);
                } else {
                    courseUser.setCourseType(userRes.getResType());
                }
                courseUser.setPlatformCode(userRes.getPlatformCode());

                courseUser.setCourseOrgId(userRes.getOrgId());
                courseUser.setCourseOrgName(userRes.getOrgName());
                courseUser.setCourseAreaId(userRes.getAreaId());
                courseUser.setLoginPlatformCode(userRes.getLoginPlatformCode());
                //从资源详情表迁移过来的7个字段，列表的where条件

                //资源有下载地址，没有fid。备课才关联附件
                if(StringUtils.isNotBlank(userRes.getFId())) {
                    courseUser.setFid(userRes.getFId());
                }
                if(Constant.IS_PACKAGE.equals(isPackage)){
                    courseUser.setTitle(userRes.getPackageName());
                    courseUser.setCourseResid(packageId);
                    courseUser.setIsPackage(isPackage);
                    courseUser.setFileExt("zip");
                    courseUser.setClassfiitonId(classfiitonIds.toString());
                }else {
                    courseUser.setTitle(tbCourseRes.getTitle());
                    courseUser.setCourseResid(uid);
                    courseUser.setFileExt(tbCourseRes.getFileExt());
                    courseUser.setClassfiitonId(userRes.getClassfiitonTypeId());
                }
                courseUser.setUserLocalPath(tbCourseRes.getUserLocalPath());
                courseUser.setMd5(tbCourseRes.getMd5());
                courseUser.setSelLabelId(tbCourseRes.getSelLabelId());
//                courseUser.setSuffix(FenbiaoUtil.getTbCourseUserSuffix(userRes.getUserId()));
                courseUser.setResSource(tbCourseRes.getResSource());
                courseUser.setResSource(tbCourseRes.getResSource());
                courseUser.setFileLength(tbCourseRes.getFileLength());

                courseUser.setCourseSubjectId(userRes.getSubjectId());
                courseUser.setCourseSubjectName(userRes.getSubjectName());
                courseUser.setCoursePeriodId(userRes.getPeriodId());
                courseUser.setCoursePeriodName(userRes.getPeriodName());
                courseUser.setCourseEditionId(userRes.getEditionId());
                courseUser.setCourseEditionName(userRes.getEditionName());
                courseUser.setCourseVolumeId(userRes.getVolumeId());
                courseUser.setCourseVolumeName(userRes.getVolumeName());
                courseUser.setCourseTextbookId(userRes.getTextbookId());
                courseUser.setCourseTextbookName(userRes.getTextbookName());
                courseUser.setCourseChapterid(userRes.getChapterId());
                courseUser.setCourseChaptername(userRes.getChapterName());
                courseUser.setIsEdit(userRes.getIsEdit());
                courseUser.setUploadCos(userRes.getUploadCos());
                //courseUser.setIsSync(isCloud ? "0" : "1");
                tbCourseUserMapper.save(courseUser);
                if(Constant.IS_PACKAGE.equals(isPackage)) {
                    TbCourseRes tbCourseRes0 = new TbCourseRes();
                    String courseId0 = UUIDUtils.getRandomUUID();
                    tbCourseRes0.setClassfiitonId(userRes.getClassfiitonTypeId());
                    tbCourseRes0.setCollectedCount(0);
                    tbCourseRes0.setCreateTime(sdf.format(new Date()));
                    tbCourseRes0.setFileExt("zip");
                    tbCourseRes0.setIntro(userRes.getIntro());
                    tbCourseRes0.setTitle(userRes.getPackageName()+".zip");
                    tbCourseRes0.setThumbnailUrl(userRes.getThumbnailUrl());
                    tbCourseRes0.setCreatorId(userRes.getUserId());
                    tbCourseRes0.setCreatorName(userRes.getUserName());
                    tbCourseRes0.setModifyTime(sdf.format(new Date()));
                    tbCourseRes0.setResId(packageId);
                    tbCourseRes0.setCourseId(courseId0);
                    tbCourseRes0.setUserLocalPath(userRes.getUserLocalPath());
                    tbCourseRes0.setOrgId(userRes.getOrgId());
                    tbCourseRes0.setOrgName(userRes.getOrgName());
                    tbCourseRes0.setResDownloadUrl(userRes.getResDownloadUrl());
                    tbCourseRes0.setIsPackage("1");
                    if(isCloud){
                        //暂无方法 先填充数据
                        tbCourseRes0.setFid(UUIDUtils.getRandomUUID());
                        tbCourseResMapper.save(tbCourseRes0);
                    }else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("userId", userRes.getUserId());
                        jsonObject.put("orgId", userRes.getOrgId());
                        jsonObject.put("packageName", tbCourseRes0.getTitle());
                        jsonObject.put("fids", fidList);
                        String resp = HttpClient.doJSONPostMethod(uploadUrl+"/resPackageUpload", jsonObject.toString());
                        //String resp = HttpClientUtil.post(SysConfig.getStrValue("upload_url")+"/resPackageUpload" ,jsonObject.toString(),null);
                        logger.info("返回结果："+resp);
                        if (resp != null && !"".equals(resp)) {
                            JSONObject obj = JSONObject.fromObject(resp);
                            String resultCode = (String) obj.get("result");
                            if (Constant.SUCCESS_CODE.endsWith(resultCode)) {
                                JSONObject dataObject = (JSONObject) obj.get("data");
                                tbCourseRes0.setFid(dataObject.optString("fid"));
                                tbCourseRes0.setResDownloadUrl(dataObject.optString("downloadUrl"));
                                tbCourseResMapper.save(tbCourseRes0);
                            }
                        }else {
                            throw new Exception("附件信息查询失败");
                        }

                    }
                }
            }
            data.put("optType","1");
            data.put("source","rrtpc");
            data.put("sourceId",courseId);
            data.put("title",userRes.getTitle());
            data.put("fileSize",userRes.getFileSize());
            data.put("fileLength",userRes.getFileLength());
            data.put("fId",attachFile.getFid());
            data.put("md5",userRes.getMd5());
            data.put("fileExt",userRes.getFileExt());
            data.put("classfiitonTypeId",userRes.getClassfiitonTypeId());
            data.put("userId",userRes.getUserId());
            data.put("userName",userRes.getUserName());
            data.put("platformCode",userRes.getLoginPlatformCode());
            data.put("loginPlatformCode",userRes.getLoginPlatformCode());
            data.put("previewUrl",previewUrl);
            data.put("downloadUrl",userRes.getDownloadUrl());
            data.put("orgId",userRes.getOrgId());
            data.put("orgName",userRes.getOrgName());
            data.put("periodId",userRes.getPeriodId());
            data.put("periodName",userRes.getPeriodName());
            data.put("subjectId",userRes.getSubjectId());
            data.put("subjectName",userRes.getSubjectName());
            data.put("editionId",userRes.getEditionId());
            data.put("editionName",userRes.getEditionName());
            data.put("volumeId",userRes.getVolumeId());
            data.put("volumeName",userRes.getVolumeName());
            data.put("textbookId",userRes.getTextbookId());
            data.put("textbookName",userRes.getTextbookName());
            data.put("chapterId",userRes.getChapterId());
            data.put("chapterName",userRes.getChapterName());
            data.put("createTime",sdf.format(new Date()));
            data.put("updateTime",sdf.format(new Date()));
            json.put("classRoomId",data.toJSONString());
            json.put("type","12");
            json.put("createTime",System.currentTimeMillis());
            json.put("userId",userRes.getUserId());
            json.put("loginPlatformCode",userRes.getLoginPlatformCode());
            json.put("jxzsResType",userRes.getJxzsResType());
            json.put("sourceResId",userRes.getPlatformResId());
            json.put("platformCode","http://rrtbk.rrt-pc.svc.cluster.local:8080/rrtbk-api/cloud/updateUsrRes");
            array.add(json.toJSONString());
        }

		map.put("courseIds", returnCourseIdList);
        map.put("resIds", returnRseIdList);
        map.put("userReslist",userReslist);
        map.put("array",array);
        return map;
    }

    @Override
    public void deleteCloud(DeleteCloudReq deleteCloudReq, String netIp) {
        List<String> ids = new ArrayList<String>();
        for (CloudId cloud : deleteCloudReq.getList()) {
            ids.add(cloud.getCourseId());
        }
        this.deleteCloud(deleteCloudReq.getUserId(), ids, netIp);
        deleteCloudReq.setIds(ids);
        //2.入kafka队列处理其他的删除操作
        deleteCloudReq.setType("1");
//        SyncTaskUtil.saveSyncTaskWorkKafkaByTheme(SysConfig.getStrValue("cousecenterapi_mysql_url") + "/cloud/batchDeleteCloudResByKafka", com.alibaba.fastjson.JSONObject.toJSONString(deleteCloudReq), "json", "post", KafkaConstant.myRes_del);
    }

    public void deleteCloud(String userId,List<String> ids,String netIp){
    	Map<String,Object> param = new HashMap<String,Object>();
		param.put("ids", ids);
		param.put("courseUserid", userId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		param.put("modifyTime", sdf.format(new Date()));
//		//删除资源信息
		batchDeleteUserRes(param);
		//删除用户资源关系
		tbCourseUserMapper.deleteCloud(param);
    }

    private void batchDeleteUserRes(Map<String, Object> map) {
		List<TbCourseUser> userResList = tbCourseUserMapper.getUserResListByMap(map);
        List<String> resIds = new ArrayList<String>();
        for(TbCourseUser res : userResList) {
			//资源id分表归类
            resIds.add(res.getCourseResid());
		}
			//分表批量删除
        Map param = new HashMap();
        param.put("courseResIds", resIds);
        param.put("modifyTime", new Date());
        if(resIds.size()>0){
            tbCourseUserMapper.deleteCloudUpdateRes(param);
        }


	}

	@Override
	public void updateResourceInfo(UpdateResourceInfo baseRequest){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TbCourseRes res = new TbCourseRes();
        res.setResId(baseRequest.getResId());
        res.setTitle(baseRequest.getName());
    	res.setModifyTime(sdf.format(new Date()));
    	tbCourseResMapper.update(res);

    	//跟新user表里的title
    	TbCourseUser t = new TbCourseUser();
    	t.setTitle(baseRequest.getName());
    	t.setCourseModifyTime(sdf.format(new Date()));
    	t.setCourseUserid(baseRequest.getUserId());
    	t.setCourseResid(baseRequest.getResId());

    	tbCourseUserMapper.updateBycourseResId(t);
    }

    /**
	 * 根据courseId查询
	 * @param resourceId
	 * @return
	 * @throws Exception
	 */
    @Override
	public TbCourseRes getResByResId(String resourceId)throws Exception{
		return this.getByResId(resourceId);
	}

	private TbCourseRes getByResId(String resId) {
    	TbCourseRes resInfo = null;
    	Map<String,Object> param = new HashMap<String,Object>();
        param.put("resId", resId);
//        param.put("suffix", FenbiaoUtil.getTbCourseResSuffix(resId));
        resInfo = tbCourseResMapper.getByResId(param);

        tbCourseResMapper.addViewCount(resId);

        return resInfo;
	}

	@Override
	public List<TbCourseRes> getResByPackageId(String packageId)throws Exception {
        return tbCourseResMapper.getByPackageId(packageId);
    }

    /**
     * 资源列表
     * @param cloudPage
     * @return
     */
    @Override
    public CloudPage<TbCourseRes> cloudList(CloudPageReq cloudPage){
        CloudPage<TbCourseRes> resPageList = new CloudPage<TbCourseRes>();
        PageInfo pageInfo = cloudPage.getPageInfo();
        if (pageInfo == null) {
            pageInfo = new PageInfo();
        }
        try {

            //我的资源列表
//            cloudPage.setSuffix(FenbiaoUtil.getTbCourseUserSuffix(cloudPage.getUserId()));
            if(StringUtil.isNotEmpty(cloudPage.getClassfiitonTypeId())){
                cloudPage.setCourseType(cloudPage.getClassfiitonTypeId());
            }
            if("1".equals(cloudPage.getClassfiitonTypeId())){
                cloudPage.setCourseType("");
                cloudPage.setIsPackage("1");
            }
            int count = tbCourseResMapper.getMyCourseResCount(cloudPage);
            pageInfo.setRecordCount(count);
            cloudPage.setStart(pageInfo.getStart());
            cloudPage.setEnd(pageInfo.getEnd());
            cloudPage.setPageSize(pageInfo.getPageSize());
            List<TbCourseRes> resList = tbCourseResMapper.getMyCourseResList(cloudPage);
            if (null != resList && !resList.isEmpty()) {
                List<String> resIds = new ArrayList<String>();
                for (TbCourseRes res : resList) {
                    resIds.add(res.getResId());

                }


                List<TbCourseRes> resInfoList = tbCourseResMapper.getByIds(resIds);
                for (TbCourseRes res : resList) {
                    if (StringUtils.isEmpty(res.getFileLength())) {
                        if (StringUtils.isNotEmpty(res.getFileSize())) {
                            res.setFileLength(String.valueOf(CovertUtil.covertFile(res.getFileSize())));
                        } else {
                            res.setFileLength("0");
                        }
                    }
                    //设置资源详情信息
                    for (int k = 0; k < resInfoList.size(); k++) {
                        TbCourseRes resInfo = resInfoList.get(k);
                        if (res.getResId().equals(resInfo.getResId())) {
                            res.setFileSize(resInfo.getFileSize());
                            if (StringUtils.isNotEmpty(resInfo.getFileLength())) {
                                res.setFileLength(resInfo.getFileLength());
                            } else {
                                res.setFileLength("0");
                            }
                            res.setPreviewUrl(resInfo.getPreviewUrl());
                            res.setResDownloadUrl(resInfo.getResDownloadUrl());
                            res.setDownUrl(resInfo.getDownUrl());
                            res.setCollectedCount(resInfo.getCollectedCount());
                            res.setThumbnailUrl(resInfo.getThumbnailUrl());
                            res.setDownCount(resInfo.getDownCount());
                            res.setViewCount(resInfo.getViewCount());
                            res.setCreatorId(resInfo.getCreatorId());
                            res.setCreatorName(resInfo.getCreatorName());
                            res.setHasReported(resInfo.getHasReported());
                            res.setSubFileExt(resInfo.getSubFileExt());
                            res.setSelLabelName(resInfo.getSelLabelName());
                            res.setSelLabelId(resInfo.getSelLabelId());
                            res.setResSource(resInfo.getResSource());
                            res.setSourceResId(resInfo.getSourceResId());
                            res.setSourcePackageId(resInfo.getSourcePackageId());
                            res.setIsPackage(resInfo.getIsPackage());
                            res.setInteractNameCh(resInfo.getInteractNameCh());
                            res.setInteractNameEn(resInfo.getInteractNameEn());
                            res.setSrcFid(resInfo.getSrcFid());
                            res.setResSource(resInfo.getResSource());
                            res.setCoursewareId(resInfo.getCoursewareId());
                            res.setJxzsResType(resInfo.getJxzsResType());
                            res.setJxzsResSourceId(resInfo.getJxzsResSourceId());
                            res.setPlatformResId(resInfo.getPlatformResId());
                            resInfoList.remove(k);
                            break;
                        }
                    }

                }
            }
            resPageList.setPageInfo(pageInfo);
            resPageList.setList(resList);

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return resPageList;
    }

    @Override
    public List<TbCourseRes> initCourseResList(CloudPageReq cloudPage) {
        return tbCourseResMapper.initCourseResList(cloudPage);
    }

    @Override
    public List<TbCourseUser> initCourseUserList(CloudPageReq cloudPage) {
        return tbCourseUserMapper.initCourseUserList(cloudPage);
    }

    @Override
    public void saveCourseResBatch(List<TbCourseRes> list) {
        tbCourseResMapper.saveCourseResBatch(list);
    }

    @Override
    public void saveCourseUserBatch(List<TbCourseUser> list) {
        tbCourseUserMapper.saveCourseUserBatch(list);
    }

    @Override
    public void syncCourseResBatch(List<Map<String, Object>> list, String type) {
        if ("INSERT".equals(type)) {
            tbCourseResMapper.syncSaveCourseResBatch(list);
        } else if ("UPDATE".equals(type)) {
            tbCourseResMapper.syncUpdateCourseResBatch(list);
        } else if ("DELETE".equals(type)) {
            tbCourseResMapper.syncDeleteCourseResBatch(list);
        }
    }

    @Override
    public void syncCourseUserBatch(List<Map<String, Object>> list, String type) {
        if ("INSERT".equals(type)) {
            tbCourseUserMapper.syncSaveCourseUserBatch(list);
        } else if ("UPDATE".equals(type)) {
            tbCourseUserMapper.syncUpdateCourseUserBatch(list);
        } else if ("DELETE".equals(type)) {
            tbCourseUserMapper.syncDeleteCourseUserBatch(list);
        }
    }

    @Override
    public void syncSaveOrUpdateCourseResBatch(List<Map<String, Object>> list) {
        tbCourseResMapper.syncSaveOrUpdateBatch(list);
    }

    @Override
    public void syncSaveOrUpdateCourseUserBatch(List<Map<String, Object>> list) {
        tbCourseUserMapper.syncSaveOrUpdateBatch(list);
    }

    @Override
    public List<Map<String, Object>> getUpSyncCourseRes() throws Exception {
        return tbCourseResMapper.getUpSyncCourseRes();
    }

    @Override
    public List<Map<String, Object>> getUpSyncCourseUser() throws Exception {
        return tbCourseUserMapper.getUpSyncCourseUser();
    }

    @Override
    public void finishUpSyncCourseRes() throws Exception {
        tbCourseResMapper.finishUpSyncCourseRes();
    }

    @Override
    public void finishUpSyncCourseUser() throws Exception {
        tbCourseUserMapper.finishUpSyncCourseUser();
    }

    @Override
    public void finishUpSyncCourseResByOrgId(String resId) throws Exception {
        tbCourseResMapper.finishUpSyncCourseResByOrgId(resId);
    }

    @Override
    public void finishUpSyncCourseUserByOrgId(String resId) throws Exception {
        tbCourseUserMapper.finishUpSyncCourseUserByOrgId(resId);
    }

    @Override
    public int statCloud(TbCourseRes tbCourseRes) throws Exception {
        return tbCourseResMapper.selectResExists(tbCourseRes);
    }

    @Override
    public void compareSyncCourseRes(List<TbCourseUser> courseUserList, List<TbCourseRes> courseResList) throws Exception {
        //List<String> compareResIdList = tbCourseUserMapper.getResIdListByUserId(userIdList);//查询所有用户资源数据
        List<TbCourseUser> courseUserInsertList = new ArrayList<TbCourseUser>();
        List<TbCourseUser> courseUserUpdateList = new ArrayList<TbCourseUser>();
        for (TbCourseUser tbCourseUser : courseUserList) {//需要同步的用户资源数据
            TbCourseUser newtbuser = tbCourseUserMapper.getById(tbCourseUser.getCourseResid());
            String updateStatUrl = rrtbkUrl + updateStat+tbCourseUser.getCourseResid()+"?accessToken=" + OpenUtil.createTokenByUrl(rrtbkUrl);
            logger.info("修改状态请求:" + updateStatUrl);
            HttpClient.doGetMethod(updateStatUrl);
            if (newtbuser==null) {
                tbCourseUser.setIsSync("0");
                courseUserInsertList.add(tbCourseUser);
            }else{
                tbCourseUser.setIsSync("0");
                courseUserUpdateList.add(tbCourseUser);
            }
        }

        if (courseUserInsertList.size() > 0) {
            tbCourseUserMapper.saveCourseUserBatch(courseUserInsertList);
        }
        if (courseUserUpdateList.size() > 0) {
            tbCourseUserMapper.updateCourseUserBatch(courseUserUpdateList);
        }


        List<TbCourseRes> courseResInsertList = new ArrayList<TbCourseRes>();
        List<TbCourseRes> courseResUpdateList = new ArrayList<TbCourseRes>();
        for (TbCourseRes tbCourseRes : courseResList) {
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("resId", tbCourseRes.getResId());
            TbCourseRes newtbres = tbCourseResMapper.getByResId(param);
            if (newtbres == null) {
                tbCourseRes.setIsSync("0");
                courseResInsertList.add(tbCourseRes);
            }else {
                tbCourseRes.setIsSync("0");
                courseResUpdateList.add(tbCourseRes);
            }
        }
        if (courseResInsertList.size() > 0) {
            tbCourseResMapper.saveCourseResBatch(courseResInsertList);
        }
        if (courseResUpdateList.size() > 0) {
            tbCourseResMapper.updateCourseResBatch(courseResUpdateList);
        }
    }

    @Override
    public void addDownCount(String resId) {
        tbCourseResMapper.addDownCount(resId);
    }

    @Override
    public void updateCloud(TbCourseRes tbCourseRes) {
        tbCourseResMapper.update(tbCourseRes);
    }

    @Override
    public void saveUserRes(com.alibaba.fastjson.JSONObject json) throws Exception {
        AttachFile attachFile = new AttachFile();
        TbCourseUser courseUser = new TbCourseUser();
        TbCourseRes  courseRes = new TbCourseRes();
        String uid = UUIDUtils.getRandomUUID();
        String fid = json.getString("fId");
        if(StringUtils.isBlank(fid)){//外部第三方资源没有fid生成新的
            fid= String.valueOf(SnowflakeUtils.getNextId());
        }else{
            //判断过来的fid有没有老的附件，有的话就新生成一条附件信息
            AttachFile oldAttachFile = attachFileDao.selectOne(Long.parseLong(fid));
            if(oldAttachFile!=null){
                fid= String.valueOf(SnowflakeUtils.getNextId());
            }
        }
        //附件信息
        attachFile.setFid(Long.parseLong(fid));
        attachFile.setFileLength(Long.parseLong(json.getString("fileLength")));
        attachFile.setFileMd5(json.getString("md5"));
        attachFile.setFileNameLocal(json.getString("title"));
        attachFile.setFileNameRemote(UUID.randomUUID().toString().replaceAll("-", "") + "." + json.getString("fileExt"));
        String filePath = FileUtil.getCosKey(attachFile.getFileNameRemote(), json.getString("userId"), json.getString("platformCode"));
        attachFile.setFilePathLocal(filePath);
        attachFile.setFilePathRemote(filePath);
        attachFile.setFilePos(Long.parseLong(json.getString("fileLength")));
        attachFile.setFileSize(json.getString("fileSize"));
        attachFile.setFileExt(json.getString("fileExt"));
        attachFile.setIsDeleted("false");
        attachFile.setPostComplete("true");
        attachFile.setPostedLength(Long.parseLong(json.getString("fileLength")));
        attachFile.setPostedPercent("100%");
        attachFile.setPostedTime(json.getDate("createTime"));
        attachFile.setUserId(json.getString("userId"));
        attachFile.setIsFileCenter("3".equals(json.getString("resSource")) ? 1 : 0);
        attachFile.setPlatformCode(json.getString("platformCode"));
        attachFile.setOrgId(json.getString("orgId"));
        attachFile.setIsPlatform("1");
        attachFile.setIsLocal("0");
        attachFile.setIsCloud("0");
        attachFile.setAttachFrom("1");
        attachFile.setDownloadUrl(json.getString("downloadUrl"));

        //资源信息
        courseRes.setResId(uid);
        courseRes.setTitle(json.getString("title"));
        courseRes.setFileSize(json.getString("fileSize"));
        courseRes.setDownCount(json.getInteger("downCount"));
        courseRes.setViewCount(json.getInteger("viewCount"));
        courseRes.setCreatorId(json.getString("userId"));
        courseRes.setCreatorName(json.getString("userName"));
        courseRes.setCreateTime(json.getString("createTime"));
        courseRes.setModifyTime(json.getString("updateTime"));
        courseRes.setFid(fid);
        courseRes.setFileExt(json.getString("fileExt"));
        courseRes.setClassfiitonId(json.getString("classfiitonTypeId"));
        courseRes.setCourseId(json.getString("sourceId"));
        courseRes.setMd5(json.getString("md5"));
        courseRes.setFileLength(json.getString("fileLength"));
        courseRes.setLoginPlatformCode(json.getString("loginPlatformCode"));
        courseRes.setDownUrl(json.getString("downloadUrl"));
        courseRes.setPreviewUrl(json.getString("previewUrl"));
        courseRes.setOrgId(json.getString("orgId"));
        courseRes.setResSource("4");
        courseRes.setCoursewareId(json.getString("coursewareId"));
        courseRes.setJxzsResType(json.getString("jxzsResType"));
        courseRes.setJxzsResSourceId(json.getString("jxzsResSourceId"));


        //课程信息
        courseUser.setFid(fid);
        courseUser.setCourseId(json.getString("sourceId"));
        courseUser.setCourseUserid(json.getString("userId"));
        courseUser.setCourseUsername(json.getString("userName"));
        courseUser.setCourseChapterid(json.getString("chapterId"));
        courseUser.setCourseChaptername(json.getString("chapterName"));
        courseUser.setCourseResid(uid);
        courseUser.setCourseCreateTime(json.getString("createTime"));
        courseUser.setCourseModifyTime(json.getString("updateTime"));
        courseUser.setLoginPlatformCode(json.getString("loginPlatformCode"));
        courseUser.setCourseStatus(Constant.COURSE_STATUS);
        courseUser.setCourseSubjectId(json.getString("subjectId"));
        courseUser.setCourseSubjectName(json.getString("subjectName"));
        courseUser.setCourseTextbookId(json.getString("textbookId"));
        courseUser.setCourseTextbookName(json.getString("textbookName"));
        courseUser.setCourseOrgId(json.getString("orgId"));
        courseUser.setFileExt(json.getString("fileExt"));
        courseUser.setTitle(json.getString("title"));
        courseUser.setClassfiitonId(json.getString("classfiitonTypeId"));
        courseUser.setMd5(json.getString("md5"));
        courseUser.setFileLength(json.getString("fileLength"));
        courseUser.setResSource("4");
        courseUser.setCoursePeriodId(json.getString("periodId"));
        courseUser.setCoursePeriodName(json.getString("periodName"));
        courseUser.setCourseEditionId(json.getString("editionId"));
        courseUser.setCourseEditionName(json.getString("editionName"));
        courseUser.setCourseVolumeId(json.getString("volumeId"));
        courseUser.setCourseVolumeName(json.getString("volumeName"));

        attachFileDao.insertOne(attachFile);
        tbCourseUserMapper.save(courseUser);
        tbCourseResMapper.save(courseRes);
    }

    @Override
    public void delUserRes(com.alibaba.fastjson.JSONObject json) throws Exception {
        tbCourseUserMapper.deleteById(json.getString("sourceId"));
        tbCourseResMapper.deleteById(json.getString("sourceId"));
    }


    @Override
    public void updateUserRes(com.alibaba.fastjson.JSONObject json) {
        TbCourseRes  courseRes = new TbCourseRes();
        courseRes.setCourseId(json.getString("sourceId"));
        courseRes.setDownUrl(json.getString("downloadUrl"));
        courseRes.setPreviewUrl(json.getString("previewUrl"));
        tbCourseResMapper.updateUserRes(courseRes);
    }

    @Override
    public void moveUserRes(com.alibaba.fastjson.JSONObject json){
        TbCourseUser courseUser = new TbCourseUser();
        courseUser.setCourseId(json.getString("sourceId"));
        courseUser.setCourseChapterid(json.getString("chapterId"));
        courseUser.setCourseChaptername(json.getString("chapterName"));
        tbCourseUserMapper.moveUserRes(courseUser);
    }

    @Override
    public void updateStatus(com.alibaba.fastjson.JSONObject json) throws Exception {
        tbCourseUserMapper.updateStatus(json.getString("sourceId"));
        tbCourseResMapper.updateStatus(json.getString("sourceId"));
    }

    @Override
    public TbCourseUser getUserByCourseId(String courseId) {
        return tbCourseUserMapper.getUserByCourseId(courseId);
    }


    @Override
    public TbCourseUser getUserByResId(String resId) {
        Map map = MapUtils.newHashMap();
        map.put("courseResId",resId);
        return tbCourseUserMapper.getById(map);
    }




    @Override
    public void updateBycourseResId(TbCourseUser tbCourseUser) {
        tbCourseUserMapper.updateBycourseResId(tbCourseUser);
    }

    @Override
    public List<TbCourseRes> queryLyData(Map map) {
        return tbCourseResMapper.queryLyData(map);
    }


    @Override
    public Map<String, Object> saveXitiCloudRes(List<UserResRequest2> userReslist,String isPackage) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> fidList = new ArrayList<String>();
        String packageId = UUIDUtils.getRandomUUID();
        List<String> returnCourseIdList = new ArrayList<String>();
        for(int i=0;i<userReslist.size();i++) {
            String courseId = UUIDUtils.getRandomUUID();
            returnCourseIdList.add(courseId);
            UserResRequest2 userRes = userReslist.get(i);

            TbCourseRes tbCourseRes = new TbCourseRes();
            String uid = UUIDUtils.getRandomUUID();

            tbCourseRes.setCollectedCount(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tbCourseRes.setCreateTime(sdf.format(new Date()));
            tbCourseRes.setFid(userRes.getFId());
            fidList.add(userRes.getFId());

            tbCourseRes.setFileExt(userRes.getFileExt());
            tbCourseRes.setIntro(userRes.getIntro());
            tbCourseRes.setTitle(userRes.getTitle());
            tbCourseRes.setThumbnailUrl(userRes.getThumbnailUrl());
            tbCourseRes.setCreatorId(userRes.getUserId());
            tbCourseRes.setCreatorName(userRes.getUserName());
            tbCourseRes.setModifyTime(sdf.format(new Date()));
            tbCourseRes.setResId(uid);
            tbCourseRes.setClassfiitonId(userRes.getClassfiitonTypeId());
            tbCourseRes.setCourseId(courseId);
            tbCourseRes.setOrgId(userRes.getOrgId());
            tbCourseRes.setOrgName(userRes.getOrgName());
            tbCourseRes.setH5Data("1");
            tbCourseRes.setCoursewareId(userRes.getCoursewareId());
            if(StringUtils.isNotEmpty(userRes.getPlatformProductCode())) {
                tbCourseRes.setPlatformProductCode(userRes.getPlatformProductCode());
            }
            if(StringUtils.isNotEmpty(userRes.getPlatformResId())) {
                tbCourseRes.setPlatformResId(userRes.getPlatformResId());
            }
            tbCourseRes.setResSource("10");//来源于习题备课
            tbCourseRes.setPlatformCode(userRes.getPlatformCode());
            tbCourseRes.setLoginPlatformCode(userRes.getLoginPlatformCode());

            if (StringUtils.isNotEmpty(userRes.getSelLabelId())) {
                tbCourseRes.setSelLabelId(userRes.getSelLabelId());
            }
            if (StringUtils.isNotEmpty(userRes.getSelLabelName())) {
                tbCourseRes.setSelLabelName(userRes.getSelLabelName());
            }
            if(Constant.IS_PACKAGE.equals(isPackage)){
                tbCourseRes.setIsPackage(packageId);
            }

            tbCourseRes.setInteractNameCh(userRes.getInteractNameCh());
            tbCourseRes.setInteractNameEn(userRes.getInteractNameEn());
            tbCourseResMapper.save(tbCourseRes);
            if(!(Constant.IS_PACKAGE.equals(isPackage)&&i != userReslist.size()-1)){
                TbCourseUser courseUser = new TbCourseUser();
                courseUser.setCourseId(courseId);
                courseUser.setCourseUserid(userRes.getUserId());
                courseUser.setCourseUsername(userRes.getUserName());
                courseUser.setCourseCreateTime(sdf.format(new Date()));
                courseUser.setCourseModifyTime(sdf.format(new Date()));
                courseUser.setCourseResid(uid);
                courseUser.setCourseStatus(Constant.COURSE_STATUS);
                if (null == userRes.getResType() || StringUtil.isEmpty(userRes.getResType())) {
                    courseUser.setCourseType(Constant.COURSE_TYPE_CREATE_BY_MY);
                } else {
                    courseUser.setCourseType(userRes.getResType());
                }
                courseUser.setPlatformCode(userRes.getPlatformCode());

                courseUser.setCourseOrgId(userRes.getOrgId());
                courseUser.setCourseOrgName(userRes.getOrgName());
                courseUser.setCourseAreaId(userRes.getAreaId());
                courseUser.setLoginPlatformCode(userRes.getLoginPlatformCode());
                //从资源详情表迁移过来的7个字段，列表的where条件
                courseUser.setFid(userRes.getFId());
                if(Constant.IS_PACKAGE.equals(isPackage)){
                    courseUser.setTitle(userRes.getPackageName());
                    courseUser.setCourseResid(packageId);
                    courseUser.setIsPackage(isPackage);
                    courseUser.setFileExt("zip");
                }else {
                    courseUser.setTitle(tbCourseRes.getTitle());
                    courseUser.setFileExt(userRes.getFileExt());
                    courseUser.setCourseResid(uid);
                }
                courseUser.setClassfiitonId(userRes.getClassfiitonTypeId());
                courseUser.setUserLocalPath(tbCourseRes.getUserLocalPath());
                courseUser.setSelLabelId(tbCourseRes.getSelLabelId());
                courseUser.setResSource("10");//来源于习题备课

                courseUser.setCourseSubjectId(userRes.getSubjectId());
                courseUser.setCourseSubjectName(userRes.getSubjectName());
                courseUser.setCoursePeriodId(userRes.getPeriodId());
                courseUser.setCoursePeriodName(userRes.getPeriodName());
                courseUser.setCourseEditionId(userRes.getEditionId());
                courseUser.setCourseEditionName(userRes.getEditionName());
                courseUser.setCourseVolumeId(userRes.getVolumeId());
                courseUser.setCourseVolumeName(userRes.getVolumeName());
                courseUser.setCourseTextbookId(userRes.getTextbookId());
                courseUser.setCourseTextbookName(userRes.getTextbookName());
                courseUser.setCourseChapterid(userRes.getChapterId());
                courseUser.setCourseChaptername(userRes.getChapterName());
                //courseUser.setIsSync(isCloud ? "0" : "1");
                tbCourseUserMapper.save(courseUser);
                if(Constant.IS_PACKAGE.equals(isPackage)) {
                    TbCourseRes tbCourseRes0 = new TbCourseRes();
                    String courseId0 = UUIDUtils.getRandomUUID();
                    tbCourseRes0.setCollectedCount(0);
                    tbCourseRes0.setCreateTime(sdf.format(new Date()));
                    tbCourseRes0.setFileExt("zip");
                    tbCourseRes0.setIntro(userRes.getIntro());
                    tbCourseRes0.setTitle(userRes.getPackageName()+".zip");
                    tbCourseRes0.setThumbnailUrl(userRes.getThumbnailUrl());
                    tbCourseRes0.setCreatorId(userRes.getUserId());
                    tbCourseRes0.setCreatorName(userRes.getUserName());
                    tbCourseRes0.setModifyTime(sdf.format(new Date()));
                    tbCourseRes0.setResId(packageId);
                    tbCourseRes0.setCourseId(courseId0);
                    tbCourseRes0.setUserLocalPath(userRes.getUserLocalPath());
                    tbCourseRes0.setOrgId(userRes.getOrgId());
                    tbCourseRes0.setOrgName(userRes.getOrgName());
                    tbCourseRes0.setResDownloadUrl(userRes.getResDownloadUrl());
                    tbCourseRes0.setIsPackage("1");
                    if(isCloud){
                        //暂无方法 先填充数据
                        tbCourseRes0.setFid(UUIDUtils.getRandomUUID());
                        tbCourseResMapper.save(tbCourseRes0);
                    }else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("userId", userRes.getUserId());
                        jsonObject.put("orgId", userRes.getOrgId());
                        jsonObject.put("packageName", tbCourseRes0.getTitle());
                        jsonObject.put("fids", fidList);
                        String resp = HttpClient.doJSONPostMethod(uploadUrl+"/resPackageUpload", jsonObject.toString());
                        logger.info("返回结果："+resp);
                        if (resp != null && !"".equals(resp)) {
                            JSONObject obj = JSONObject.fromObject(resp);
                            String resultCode = (String) obj.get("result");
                            if (Constant.SUCCESS_CODE.endsWith(resultCode)) {
                                JSONObject dataObject = (JSONObject) obj.get("data");
                                tbCourseRes0.setFid(dataObject.optString("fid"));
                                tbCourseRes0.setResDownloadUrl(dataObject.optString("downloadUrl"));
                                tbCourseResMapper.save(tbCourseRes0);
                            }
                        }else {
                            throw new Exception("附件信息查询失败");
                        }

                    }
                }
            }

        }

        map.put("courseIds", returnCourseIdList);
        return map;
    }



    @Override
    @Transactional
    public Map<String, Object> saveShangHaiCloudRes(List<UserResRequest2> userReslist) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> returnCourseIdList = new ArrayList<String>();
        for(int i=0;i<userReslist.size();i++) {
            String courseId = UUIDUtils.getRandomUUID();
            returnCourseIdList.add(courseId);
            UserResRequest2 userRes = userReslist.get(i);
            TbCourseRes tbCourseRes = new TbCourseRes();
            String uid = userRes.getShangHaiResId();

            tbCourseRes.setCollectedCount(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tbCourseRes.setCreateTime(sdf.format(new Date()));
            tbCourseRes.setFid(userRes.getFId());

            tbCourseRes.setFileExt(userRes.getFileExt());
            tbCourseRes.setIntro(userRes.getIntro());
            tbCourseRes.setTitle(userRes.getTitle());
            tbCourseRes.setThumbnailUrl(userRes.getThumbnailUrl());
            tbCourseRes.setCreatorId(userRes.getUserId());
            tbCourseRes.setCreatorName(userRes.getUserName());
            tbCourseRes.setModifyTime(sdf.format(new Date()));
            tbCourseRes.setResId(uid);
            tbCourseRes.setClassfiitonId(userRes.getClassfiitonTypeId());
            tbCourseRes.setCourseId(courseId);
            tbCourseRes.setOrgId(userRes.getOrgId());
            tbCourseRes.setOrgName(userRes.getOrgName());
            tbCourseRes.setH5Data("1");
            tbCourseRes.setJxzsResType("101");
            tbCourseRes.setCoursewareId(userRes.getCoursewareId());
            if(StringUtils.isNotEmpty(userRes.getPlatformProductCode())) {
                tbCourseRes.setPlatformProductCode(userRes.getPlatformProductCode());
            }
            if(StringUtils.isNotEmpty(userRes.getPlatformResId())) {
                tbCourseRes.setPlatformResId(userRes.getPlatformResId());
            }
            tbCourseRes.setResSource("101");//来源于习题备课
            tbCourseRes.setPlatformCode(userRes.getPlatformCode());
            tbCourseRes.setLoginPlatformCode(userRes.getLoginPlatformCode());

            if (StringUtils.isNotEmpty(userRes.getSelLabelId())) {
                tbCourseRes.setSelLabelId(userRes.getSelLabelId());
            }
            if (StringUtils.isNotEmpty(userRes.getSelLabelName())) {
                tbCourseRes.setSelLabelName(userRes.getSelLabelName());
            }

            tbCourseRes.setPreviewUrl(userRes.getPreviewUrl());
            tbCourseRes.setDownUrl(userRes.getDownloadUrl());
            tbCourseRes.setInteractNameCh(userRes.getInteractNameCh());
            tbCourseRes.setInteractNameEn(userRes.getInteractNameEn());
            tbCourseResMapper.save(tbCourseRes);

            JSONObject bianmuInfo =  getUserChapter(userRes.getUserId(),userRes.getPlatformCode(),userRes.getLoginPlatformCode());

            TbCourseUser courseUser = new TbCourseUser();
            courseUser.setCourseId(courseId);
            courseUser.setCourseUserid(userRes.getUserId());
            courseUser.setCourseUsername(userRes.getUserName());
            courseUser.setCourseCreateTime(sdf.format(new Date()));
            courseUser.setCourseModifyTime(sdf.format(new Date()));
            courseUser.setCourseResid(uid);
            courseUser.setCourseStatus(Constant.COURSE_STATUS);
            if (null == userRes.getResType() || StringUtil.isEmpty(userRes.getResType())) {
                courseUser.setCourseType(Constant.COURSE_TYPE_CREATE_BY_MY);
            } else {
                courseUser.setCourseType(userRes.getResType());
            }
            courseUser.setPlatformCode(userRes.getPlatformCode());

            courseUser.setCourseOrgId(userRes.getOrgId());
            courseUser.setCourseOrgName(userRes.getOrgName());
            courseUser.setCourseAreaId(userRes.getAreaId());
            courseUser.setLoginPlatformCode(userRes.getLoginPlatformCode());
            //从资源详情表迁移过来的7个字段，列表的where条件
            courseUser.setFid(userRes.getFId());

            courseUser.setTitle(tbCourseRes.getTitle());
            courseUser.setFileExt(userRes.getFileExt());
            courseUser.setCourseResid(uid);

            courseUser.setClassfiitonId(userRes.getClassfiitonTypeId());
            courseUser.setUserLocalPath(tbCourseRes.getUserLocalPath());
            courseUser.setSelLabelId(tbCourseRes.getSelLabelId());
            courseUser.setResSource("101");//来源于习题备课

            courseUser.setCourseSubjectId(bianmuInfo.getString("subjectId"));
            courseUser.setCourseSubjectName(bianmuInfo.getString("subjectName"));
            courseUser.setCoursePeriodId(bianmuInfo.getString("periodId"));
            courseUser.setCoursePeriodName(bianmuInfo.getString("periodName"));
            courseUser.setCourseEditionId(bianmuInfo.getString("editionId"));
            courseUser.setCourseEditionName(bianmuInfo.getString("editionName"));
            courseUser.setCourseVolumeId(bianmuInfo.getString("volumeId"));
            courseUser.setCourseVolumeName(bianmuInfo.getString("volumeName"));
            courseUser.setCourseTextbookId(bianmuInfo.getString("textbookId"));
            courseUser.setCourseTextbookName(bianmuInfo.getString("textbookName"));
            courseUser.setCourseChapterid(bianmuInfo.getString("chapterId"));
            courseUser.setCourseChaptername(bianmuInfo.getString("chapterName"));
            tbCourseUserMapper.save(courseUser);
        }

        map.put("courseIds", returnCourseIdList);
        return map;
    }



    @Override
    public void deleteShangHaiCloud(List<String> resIdList) {
        tbCourseResMapper.deleteShangHaiRes(resIdList);
        tbCourseUserMapper.deleteShangHaiRes(resIdList);
    }




    private JSONObject getUserChapter(String userId,String platformCode,String loginPlatformCode) throws Exception {
        String url = "https://gateway.huijiaoyun.com/res-course/userTextBook/getUserChapter?accessToken="+OpenUtil.createToken();
        com.alibaba.fastjson.JSONObject param = new com.alibaba.fastjson.JSONObject();
        param.put("userSessionId","userSessionId");
        param.put("userId",userId);
        param.put("platformCode",platformCode);
        param.put("loginPlatformCode",loginPlatformCode);
        String aamResponse = HttpClient.doJSONPostMethod(url, param.toJSONString());
        net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
        String resultCode = jsonObj.optString("result");
        if (Constant.SUCCESS_CODE.equals(resultCode)) {
            JSONObject data = jsonObj.optJSONObject("data");
            return  data;
        }else{
            return null;
        }
    }




}
